package cn.bitkit.component.log;

import com.alibaba.fastjson2.filter.ValueFilter;
import cn.bitkit.base.annotation.Sensitive;
import cn.bitkit.base.constants.SensitiveType;
import cn.bitkit.base.util.ReflectUtil;
import cn.bitkit.tools.data.MaskUtil;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;

@Slf4j
public class LogSensitiveFilter implements ValueFilter {

	@Override
	public Object apply(Object object, String name, Object value) {
		if(object == null) {
			return null;
		}
		try {
			if(!(value instanceof String)) {
				return value;
			}
			Field field = ReflectUtil.getField(object.getClass(), name);
			if(field == null){
				return value;
			}
			Sensitive sensitive = field.getAnnotation(Sensitive.class);
			if(sensitive == null) {
				return value;
			}
			String val = value.toString();
			String text = "";
			if(SensitiveType.name.equals(sensitive.type())) {
				text = MaskUtil.name(val);
			}
			if(SensitiveType.phone.equals(sensitive.type())) {
				text = MaskUtil.phone(val);
			}
			if(SensitiveType.email.equals(sensitive.type())) {
				text = MaskUtil.email(val);
			}
			if(SensitiveType.bankCard.equals(sensitive.type())) {
				text = MaskUtil.bankCard(val);
			}
			if(SensitiveType.idCard.equals(sensitive.type())) {
				text = MaskUtil.idCard(val);
			}
			return text;
		} catch (Exception e) {
			log.error("", e);
		}
		return null;
	}
}
